// 结果分析页面JavaScript
document.addEventListener('DOMContentLoaded', function() {
    // 检查当前页面是哪个，以决定执行哪种初始化
    const currentPath = window.location.pathname;
    
    if (currentPath === '/results' || currentPath === '/results/') {
        // 加载结果分析页面
        loadResults();
        updateResultStats();
        
        // 刷新按钮事件
        document.getElementById('refreshResultsBtn').addEventListener('click', loadResults);
    }
});

function loadResults() {
    // 从API获取结果数据
    fetch('/api/results')
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            const tableBody = document.querySelector('#resultsTable tbody');
            tableBody.innerHTML = '';

            // 如果API返回的格式是直接的数组
            const results = Array.isArray(data) ? data : data.results || [];
            
            results.forEach(result => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td><input type="checkbox" class="result-checkbox" value="${result.id}"></td>
                    <td>${result.id}</td>
                    <td>${result.task_id || 'N/A'}</td>
                    <td>${result.worker_name || 'N/A'}</td>
                    <td>${result.test_case_name || 'N/A'}</td>
                    <td>
                        <span class="badge ${getResultStatusBadgeClass(result.result?.status)}">
                            ${getResultStatusDisplayName(result.result?.status)}
                        </span>
                    </td>
                    <td>${result.result?.read?.iops || 'N/A'}</td>
                    <td>${result.result?.write?.iops || 'N/A'}</td>
                    <td>${result.result?.latency?.avg || 'N/A'} ms</td>
                    <td>
                        <button class="btn btn-sm btn-info" onclick="viewResult('${result.id}')">查看</button>
                        <button class="btn btn-sm btn-warning" onclick="analyzeResult('${result.id}')">分析</button>
                        <button class="btn btn-sm btn-danger" onclick="deleteResult('${result.id}')">删除</button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
            
            // 更新图表
            updateCharts(results);
        })
        .catch(error => {
            console.error('Error loading results:', error);
            // 如果API调用失败，显示错误信息
            const tableBody = document.querySelector('#resultsTable tbody');
            tableBody.innerHTML = `<tr><td colspan="10" class="text-center text-danger">加载结果失败: ${error.message}</td></tr>`;
        });
}

function updateResultStats() {
    // 从API获取统计信息
    fetch('/api/results/summary')
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            document.getElementById('totalTests').textContent = data.total_tests || '0';
            document.getElementById('avgIOPS').textContent = data.avg_iops || 'N/A';
            document.getElementById('avgLatency').textContent = data.avg_latency ? `${data.avg_latency.toFixed(2)} ms` : 'N/A';
            document.getElementById('avgBandwidth').textContent = data.avg_bandwidth ? `${(data.avg_bandwidth / 1024 / 1024).toFixed(2)} MB/s` : 'N/A';
        })
        .catch(error => {
            console.error('Error updating stats:', error);
            document.getElementById('totalTests').textContent = 'Error';
            document.getElementById('avgIOPS').textContent = 'Error';
            document.getElementById('avgLatency').textContent = 'Error';
            document.getElementById('avgBandwidth').textContent = 'Error';
        });
}

// 获取结果状态徽章类
function getResultStatusBadgeClass(status) {
    const statusClasses = {
        'completed': 'bg-success',
        'failed': 'bg-danger',
        'running': 'bg-warning'
    };
    return statusClasses[status] || 'bg-secondary';
}

// 获取结果状态显示名称
function getResultStatusDisplayName(status) {
    const statusNames = {
        'completed': '已完成',
        'failed': '失败',
        'running': '运行中'
    };
    return statusNames[status] || status || '未知';
}

// 查看结果
function viewResult(id) {
    alert('查看结果: ' + id);
}

// 分析结果
function analyzeResult(id) {
    alert('分析结果: ' + id);
}

// 删除结果
function deleteResult(id) {
    if (confirm('确定要删除这个结果吗？')) {
        fetch(`/api/results/${id}`, {
            method: 'DELETE'
        })
        .then(response => {
            if (response.ok) {
                alert('结果删除成功！');
                loadResults(); // 重新加载数据
                updateResultStats();
            } else {
                throw new Error('删除结果失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('删除结果时出错: ' + error.message);
        });
    }
}

// 更新图表
function updateCharts(results) {
    // 这里应该是实际的图表更新逻辑
    // 暂时使用真实数据来演示
    console.log('Updating charts with results:', results);
    
    // 示例：IOPS对比图
    updateIOPSChart(results);
    
    // 示例：延迟对比图
    updateLatencyChart(results);
    
    // 示例：带宽对比图
    updateBandwidthChart(results);
}

// 更新IOPS图表
function updateIOPSChart(results) {
    // 这里应该是实际的图表绘制逻辑
    console.log('Updating IOPS chart with results:', results);
}

// 更新延迟图表
function updateLatencyChart(results) {
    // 这里应该是实际的图表绘制逻辑
    console.log('Updating latency chart with results:', results);
}

// 更新带宽图表
function updateBandwidthChart(results) {
    // 这里应该是实际的图表绘制逻辑
    console.log('Updating bandwidth chart with results:', results);
}

// 加载测试用例用于过滤
function loadTestCasesForFilter() {
    fetch('/api/test-cases')
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            // 如果API返回的格式是直接的数组
            const testCases = Array.isArray(data) ? data : data.test_cases || [];
            
            const select = document.getElementById('testCaseFilter');
            select.innerHTML = '<option value="">全部测试用例</option>';
            
            testCases.forEach(testCase => {
                const option = document.createElement('option');
                option.value = testCase.id;
                option.textContent = testCase.name;
                select.appendChild(option);
            });
        })
        .catch(error => {
            console.error('Error loading test cases for filter:', error);
        });
}

// 应用过滤条件
function applyFilters() {
    const testCaseId = document.getElementById('testCaseFilter').value;
    const workerId = document.getElementById('workerFilter').value;
    const dateRange = document.getElementById('dateRangeFilter').value;
    
    // 构建查询参数
    const params = new URLSearchParams();
    if (testCaseId) params.append('test_case_id', testCaseId);
    if (workerId) params.append('worker_id', workerId);
    if (dateRange) params.append('date_range', dateRange);
    
    // 从API获取过滤后的结果
    fetch(`/api/results?${params.toString()}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            const tableBody = document.querySelector('#resultsTable tbody');
            tableBody.innerHTML = '';

            // 如果API返回的格式是直接的数组
            const results = Array.isArray(data) ? data : data.results || [];
            
            results.forEach(result => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td><input type="checkbox" class="result-checkbox" value="${result.id}"></td>
                    <td>${result.id}</td>
                    <td>${result.task_id || 'N/A'}</td>
                    <td>${result.worker_name || 'N/A'}</td>
                    <td>${result.test_case_name || 'N/A'}</td>
                    <td>
                        <span class="badge ${getResultStatusBadgeClass(result.result?.status)}">
                            ${getResultStatusDisplayName(result.result?.status)}
                        </span>
                    </td>
                    <td>${result.result?.read?.iops || 'N/A'}</td>
                    <td>${result.result?.write?.iops || 'N/A'}</td>
                    <td>${result.result?.latency?.avg || 'N/A'} ms</td>
                    <td>
                        <button class="btn btn-sm btn-info" onclick="viewResult('${result.id}')">查看</button>
                        <button class="btn btn-sm btn-warning" onclick="analyzeResult('${result.id}')">分析</button>
                        <button class="btn btn-sm btn-danger" onclick="deleteResult('${result.id}')">删除</button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
            
            // 更新图表
            updateCharts(results);
        })
        .catch(error => {
            console.error('Error applying filters:', error);
            alert('应用过滤条件时出错: ' + error.message);
        });
}

// 导出结果
function exportResults() {
    const format = document.getElementById('exportFormat').value;
    
    if (!format) {
        alert('请选择导出格式');
        return;
    }
    
    // 构建导出URL
    const exportUrl = `/api/results/export?format=${format}`;
    
    // 触发下载
    window.open(exportUrl, '_blank');
}

// 批量删除结果
function batchDeleteResults() {
    const checkboxes = document.querySelectorAll('.result-checkbox:checked');
    
    if (checkboxes.length === 0) {
        alert('请至少选择一个结果进行删除');
        return;
    }
    
    if (confirm(`确定要删除选中的 ${checkboxes.length} 个结果吗？`)) {
        const ids = Array.from(checkboxes).map(cb => cb.value);
        
        // 发送批量删除请求
        fetch('/api/results/batch-delete', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ ids: ids })
        })
        .then(response => {
            if (response.ok) {
                alert('结果批量删除成功！');
                loadResults(); // 重新加载数据
                updateResultStats();
            } else {
                throw new Error('批量删除结果失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('批量删除结果时出错: ' + error.message);
        });
    }
}